

<template>
  <!--<div class="app-container"> -->
  <el-container style="width: 100%; height: 90%">
    <el-container style="width: 100%; height: 90%">
      <el-aside
        style="
          padding: 10px;
          width: 44.5%;
          height: 100%;
          background-color: white;
          overflow: hidden;
        "
      >
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
              >上传</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleInvalid"
              >无效分析</el-button
            >
          </el-col>
        </el-row>
        <div class="line mt-10"></div>
        <el-row class="input-distanct">
          <el-col :span="4.5">
            <el-form
              :model="queryParams"
              ref="queryForm"
              :inline="true"
              label-width="68px"
            >
              <el-form-item prop="fileName">
                <!-- <el-date-picker
                  clearable
                  size="small"
                  style="width: 150px"
                  v-model="queryParams.createTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择上传时间"
                ></el-date-picker> -->
                <el-input
                  size="small"
                  v-model="queryParams.fileName"
                  placeholder="请填写图片名称"
                ></el-input>
              </el-form-item>
              <el-button
                icon="el-icon-search"
                class="mt-5"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form>
          </el-col>
        </el-row>

        <el-table
          :border="true"
          size="mini"
          height="680px"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @expand-change="showImage"
          :data="imageDataList"
          @row-dblclick="showImage"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" width="40px" />
          <el-table-column type="expand" label="结果" width="50px">
            <template>
              <el-table
                v-loading="loading"
                size="mini"
                :show-header="false"
                style="width: 500px"
                :data="showImageResults"
              >
                <el-table-column
                  prop="resultType"
                  label="绝缘子结果"
                  width="380px"
                >
                  <template slot-scope="scope">
                    <template>
                      <div v-for="result in imageResults" :key="result.value">
                        <span
                          v-if="result.value == scope.row.resultType"
                          v-text="result.label"
                        ></span>
                      </div>
                    </template>
                    <!-- <div v-if="specialImg">
                      <span>污秽绝缘子</span>
                    </div> -->
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                  class-name="small-padding "
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-check"
                      @click="checkResult(scope.row)"
                    >
                      <span
                        v-for="check in resultCheck"
                        v-if="check.value == scope.row.delFlag"
                        v-text="check.label"
                        :key="check.value"
                      ></span>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>

          <el-table-column
            width="85px"
            label="上传时间"
            align="center"
            prop="createTime"
          >
            <template slot-scope="scope">
              <span>{{
                $moment(scope.row.createTime).format("YYYY-MM-DD")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="85px"
            label="线路名称"
            align="center"
            prop="lineName"
          />
          <el-table-column
            width="85px"
            label="图片名称"
            align="center"
            prop="fileName"
          />
          <el-table-column
            width="75px"
            label="电压等级"
            align="center"
            prop="voltageClass"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-magic-stick"
                @click="handleAnalysis(scope.row)"
                >重新分析</el-button
              >
              <el-button
                style="margin-left: 0"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleInvalid(scope.row)"
                >无效分析</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          :pager-count="5"
          small
          @pagination="getList"
        />
      </el-aside>

      <el-main style="background-color: #f8f8f9">
        <div class="align-center mb-10">
          <el-button type size="medium" @click="handleAdjustSize(0.75)"
            >缩小1.5倍</el-button
          >
          <el-button type size="medium" @click="handleAdjustSize(0.5)"
            >缩小2倍</el-button
          >
          <el-button type size="medium" @click="handleAdjustSize(1.5)"
            >放大1.5倍</el-button
          >
          <el-button type size="medium" @click="handleAdjustSize(2)"
            >放大2倍</el-button
          >
        </div>
        <img
          :src="src"
          v-if="showImageResults[0]"
          :width="showImageResults[0].imageWidth"
          :height="showImageResults[0].imageHeight"
          class="absolute"
          alt
        />
        <canvas
          id="myCanvas"
          v-if="showImageResults[0]"
          :width="showImageResults[0].imageWidth"
          :height="showImageResults[0].imageHeight"
          style="position: absolute"
        ></canvas>
        <!-- <img :src="src" alt="" /> -->
      </el-main>
    </el-container>

    <!-- 添加或修改文件上传对话框 -->
    <el-dialog
      :title="title"
      :modal="true"
      :visible.sync="open"
      width="450px"
      style="position: absolute"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="95px"
        label-position="left"
      >
        <el-form-item label="线路名称" prop="uploader">
          <el-input v-model="form.lineName" placeholder="请输入线路名称" />
        </el-form-item>
        <el-form-item label="绝缘子类型" prop="type" class="mt-20">
          <el-select v-model="form.type" placeholder="请选择绝缘子类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电压等级" prop="voltageClass" class="mt-20">
          <el-select
            v-model="form.voltageClass"
            placeholder="请选择电压等级"
            @change="handleChangeVoltage"
          >
            <el-option
              v-for="item in voltageClassOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark" class="mt-20">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

        <!-- <el-form-item label="上传" class="mt-20">
              <input type="file" ref="fileBtn" @change="changeUpload" />
            </el-form-item> -->
      </el-form>
      <!-- <form
            action="http://192.168.0.132:8000/file/"
            enctype="multipart/form-data"
            method="post"
          >
            <input name="file" type="file" />
            <input type="submit" value="uploadFile上传" />
          </form> -->
      <el-upload
        :action="baseurl + '/file/'"
        multiple
        :auto-upload="false"
        :data="form"
        :file-list="fileList"
        :on-success="handleSuccess"
        ref="uplodas"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </el-container>

  <!--</div>-->
</template>  
    
  <script>
import pagination from "../../../../components/Pagination/index";
import http from "../../../../utils/http";
import {
  insertFileData,
  getFileData,
  delFileData,
  updateFileData,
  getFileDataCount,
  handleInvalid,
  invalidResult,
} from "../../../../db/model/fileData/db";
import {
  getResultByDataId,
  updateResult,
} from "../../../../db/model/fileDataResult/FDRdb";
import { getResult, getReanalyse } from "../../../../api/index";

let canvas;
let ctx;
export default {
  name: "Upload",
  data() {
    return {
      //图片绝缘子类型结果字典
      imageResults: [
        {
          label: "正常绝缘子",
          value: "1",
          name: "正常",
        },
        {
          label: "零值绝缘子",
          value: "2",
          name: "零值",
        },
        {
          label: "低值绝缘子",
          value: "3",
          name: "低值",
        },
        {
          label: "污秽绝缘子",
          value: "4",
          name: "污秽",
        },
      ],
      baseurl: _baseUrl,
      //电压等级下拉框选择
      voltageClassOptions: [
        {
          label: "110kv",
          value: "1",
        },
        {
          label: "220kv",
          value: "2",
        },
        {
          label: "500kv",
          value: "3",
        },
        {
          label: "其他",
          value: "4",
        },
      ],
      //绝缘子类型下拉框选择
      typeOptions: [
        {
          label: "玻璃绝缘子",
          value: "0",
        },
        {
          label: "瓷质绝缘子",
          value: "1",
        },
      ],
      //实现只展开一个表格
      expands: [], //只展开一行放入当前行id
      getRowKeys: (row) => {
        return row._id; //这里看这一行中需要根据哪个属性值是id
      },
      //图片放大预览
      imageList: [],
      //图片显示
      src: null,
      //文件信息列表
      fileList: [],
      //跟随文件一起传过去的信息
      fileData: [],
      //用于显示的图片结果列表
      showImageResults: [],
      image: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 图片数据列表
      imageDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 图片类型字典
      imageTypeOptions: [],
      fileUploads: [],
      uplodaData: {},
      firstStepFalg: true,
      taskMatterId: null,
      fileList: [],
      lineColor: "red", //当前的线的颜色
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createTime: undefined,
        fileName: "", //查询的文件名、
        type: undefined,
      },
      // 表单参数
      form: {
        // delFlag: null, //状态（0正常 1关闭）
        // createTime: null, //创建时间
        type: null, //类型
        voltageClass: null, //备注
        // imageType: null, //图片类型
        // lineName: null, //线路名称
        // imageData: null,
      },
      // 表单校验
      rules: {
        type: [
          { required: true, message: "绝缘子类型不能为空", trigger: "change" },
        ],
        voltageClass: [
          { required: true, message: "电压等级不能为空", trigger: "change" },
        ],
        // lineName: [
        //   { required: true, message: "线路名称不能为空", trigger: "change" },
        // ],
      },
      //绝缘子结果确认字典
      resultCheck: [
        {
          label: "待确认",
          value: 0,
        },
        {
          label: "已确认",
          value: 1,
        },
      ],
      points: [], //点的坐标
      // specialImg: false, //特殊图片--污秽
    };
  },
  mounted() {
    this.getList();
  },
  components: {
    pagination,
  },
  methods: {
    //绝缘子类型的选择改变
    handleChangetType(val) {
      this.form.type = val;
      this.rules.type = { type: this.rules.type };
      this.$forceUpdate();
    },
    //电压等级的选择改变
    handleChangeVoltage(val) {
      this.form.voltageClass = val;
      this.rules.voltageClass = { voltageClass: this.rules.voltageClass };
      this.$forceUpdate();
    },
    //将上传的图片转化为base64
    changeUpload(even) {
      let _this = this;
      // var reader = new FileReader(); //创建读取文件的方法

      // var img1 = this.$refs.fileBtn.files[0];

      // reader.readAsDataURL(img1); //将文件已url的形式读入页面

      // reader.onloadend = function () {
      //   _this.$set(_this.form, "imageData", img1); //把图片的二进制流付给表单ruleForm里面的idImage

      // };

      let data = {
        data: { name: "zdj" },
        file: { image01: param },
      };

      result(data).then((res) => {
        console.log(res, "11111");
      });
    },
    /**   查看图片数据和结果数据*/
    showImage(row, expandedRows) {
      //结果回收时不执行下面代码
      if (expandedRows != undefined) {
        if (expandedRows.length == 0) {
          return;
        }
      }
      //预览图片列表清空
      this.imageList = [];
      //图片img显示
      console.log(row.fileName, "row");
      //当图片名称为 20190922_105614 时 specialImg
      // if (row.fileName == "20190922_105614.bmp") {
      //   this.specialImg = true;
      // } else {
      //   //当图片名称不为这个的时候 将特殊图片标记重置为false
      //   this.specialImg = false;
      // }
      getResult(row.fileId).then((res) => {
        this.src = "data:image/png;base64," + res.data;
        this.handleAdjustSize(1);
      });
      // this.src = "data:image/png;base64," + row.imageData;
      this.handleImageResults(row, expandedRows);
    },
    /**多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item._id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 查询图片列表 */
    getList() {
      this.loading = true;
      getFileData(this.queryParams).then((res) => {
        this.imageDataList = JSON.parse(JSON.stringify(res));
        getFileDataCount(this.queryParams).then((res) => {
          this.total = res;
          this.loading = false;
        });
      });
    },
    /** 重新分析  */
    handleAnalysis(row) {
      console.log(row);
      getReanalyse({
        dataId: row._id,
        fileId: row.fileId,
      }).then((res) => {
        this.getList();
        this.expands = [];
      });
    },
    /**  确认绝缘子结果    */
    checkResult(row) {
      let number = parseInt(row.delFlag);
      if (number) {
        console.log(number, 111);
        return;
      }
      number = 1;

      updateResult({ _id: row._id }, { delFlag: number }).then((res) => {
        this.lineColor = "orange";
        this.handleAdjustSize(1);
        getResultByDataId(row.fileDataId).then((res) => {
          console.log(res);
          this.showImageResults = JSON.parse(JSON.stringify(res));
          this.expands = [];
          this.expands.push(row.fileDataId);
        });
      });
    },
    /**    无效分析处理  */
    handleInvalid(row) {
      let vm = this;
      const ids = row._id || this.ids;
      this.$confirm('是否确认无效分析处理为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          vm.loading = true;
          if (row._id) {
            invalidResult({ _id: row._id }, { delFlag: 1 }).then((res) => {
              return true;
            });
          } else {
            for (let i = 0; i < ids.length; i++) {
              invalidResult({ _id: ids[i] }, { delFlag: 1 }).then((res) => {
                return true;
              });
            }
          }
        })
        .then((response) => {
          vm.loading = false;
          this.showImageResults = [];
          this.getList();
        });
    },
    //调整结果的大小
    handleAdjustSize(size) {
      //控制当满足什么条件的时候 图片和帆布大小将不再缩放
      if (
        ((this.showImageResults[0].imageWidth < 200 ||
          this.showImageResults[0].imageHeight < 150) &&
          size < 1) ||
        ((this.showImageResults[0].imageWidth > 1000 ||
          this.showImageResults[0].imageHeight > 800) &&
          size > 1)
      ) {
        return;
      }
      this.points = [];
      //调整图片和帆布的大小
      this.showImageResults[0].imageWidth *= size;
      this.showImageResults[0].imageHeight *= size;
      //调整坐标点的大小
      this.showImageResults[0].resultContent.forEach((val) => {
        val[0] *= size;
        val[1] *= size;
        this.points.push([val[0], val[1]]);
      });

      setTimeout(() => {
        this.initCanvas();
      }, 1800); //解决动态改变canvas宽度之后渲染元素，会导致渲染失败
    },
    //初始化帆布
    initCanvas() {
      let canvas = document.getElementById("myCanvas");
      let ctx = canvas.getContext("2d");
      ctx.strokeStyle = this.lineColor;
      let pointsLength = this.points.length;
      ctx.moveTo(this.points[0][0], this.points[0][1]); //起点
      this.points.forEach((val) => {
        ctx.lineTo(val[0], val[1]);
      }); //根据坐标点连接成线
      let lastPointX = this.points[pointsLength - 1][0]; //最后一个点的坐标x
      let lastPointY = this.points[pointsLength - 1][1]; //最后一个点的坐标y
      ctx.lineTo(lastPointX + 50, lastPointY - 50);
      ctx.lineTo(lastPointX + 80, lastPointY - 50);
      ctx.stroke();

      //开始画圆
      ctx.fillStyle = this.lineColor;
      ctx.beginPath();
      ctx.arc(
        lastPointX + 100,
        lastPointY - 50,
        20,
        -lastPointX - 100,
        2 * Math.PI
      );
      ctx.fill();
      ctx.closePath();
      ctx.fillStyle = "#fff";
      ctx.font = "14px Arial";
      // 绝缘子结果的类型过滤
      let values = "";
      // if (!this.specialImg) {
      //   this.imageResults.filter((val) => {
      //     if (val.value == this.showImageResults[0].resultType) {
      //       values = val.name;
      //     }
      //   });
      // } else {
      //   values = "污秽";
      // }
      ctx.fillText(values, lastPointX + 85, lastPointY - 45);
    },
    handleUploadSucess() {
      this.getList();
    },
    /** 图片结果列表 */
    handleImageResults(row, expandedRows) {
      this.reset();
      this.showImageResults = [];
      // this.expands = [];
      /**获得图片结果列表  */
      getResultByDataId(row._id).then((res) => {
        this.showImageResults = JSON.parse(JSON.stringify(res));
        this.expands = [];
        this.expands.push(row._id);
        //点击展开的时候 如果delflag为1 就是已经确认过 置为黄色
        if (this.showImageResults[0].delFlag == "1") {
          this.lineColor = "orange";
        } else {
          this.lineColor = "red";
        }

        this.handleAdjustSize(1);
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      //  this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        uploader: undefined,
        uploadTime: undefined,
        type: undefined,
        remark: undefined,
        imageType: undefined,
      };
      this.fileUploads = [];
      this.uplodaData = {};
      this.fileList = [];
      this.$nextTick(() => {
        if (this.$refs["form"] !== undefined) {
          this.$refs["form"].resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(1111);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.$nextTick(() => {
      this.$refs["queryForm"].resetFields();
      // });
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件上传";
    },
    //点击上传文件
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$refs.uplodas.submit();
        }
      });
    },
    //上传文件成功后关闭弹窗 获取列表
    handleSuccess() {
      this.open = false;
      this.$nextTick(() => {
        this.getList();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 0;
}
// 按钮的圆角统一
/deep/.el-button {
  border-radius: 4px;
}
// 上下的间距统一
/deep/.el-input--small {
  .el-input__inner {
    height: 28px;
  }
}
/deep/.el-form-item {
  vertical-align: middle;
}
.input-distanct {
  margin: 3px 0 5px 0;
}
/deep/.el-table--scrollable-x {
  .el-table__body-wrapper {
    overflow-x: hidden;
  }
}
/deep/.el-table--scrollable-x {
  .el-table__body-wrapper {
    overflow-x: hidden;
  }
}
/deep/ .el-dialog__body {
  overflow-y: auto;
  height: 300px;
}
.line {
  height: 1px;
  background-color: #d6d8dd;
}
/deep/.el-table thead {
  color: #333;
}
/deep/.el-pagination {
  /deep/.el-select {
    /deep/.el-input {
      /deep/.el-input__inner {
        height: 22px;
      }
    }
  }
}
</style>

<style>
.el-table__expanded-cell[class*="cell"] {
  padding: 20px 29px !important;
}
</style>